<template>
  <div>
    <router-view></router-view>

    <Menu></Menu>
    <div><button @click="showAddbook">添加book</button></div>
    <h2>书籍列表</h2>
    <ul>
      <li v-for="book in books" :key="book.id">
        <h3>{{ book.title }}</h3>
        <p>作者: {{ book.author }}</p>
        <button @click="goDetail(book.id)">详情</button>
        <button @click="deleteBook(book.id)">删除</button>
      </li>
    </ul>
    <div v-show="addbookmodalstate" class="addbookmodal">
      <p>
        <input v-model="book.title" type="text" placeholder="书名" />
      </p>
      <p>
        <input v-model="book.author" type="text" placeholder="作者" />
      </p>
      <p>
        <input v-model="book.price" type="text" placeholder="价格" />
      </p>
      <p>
        <input v-model="book.publish" type="text" placeholder="出版社" />
      </p>
      <p>
        <button @click="addbook">添加</button>
      </p>
    </div>
  </div>
</template>

<script>
import axios from "axios";

import Menu from "@/components/Menu.vue";
export default {
  name: "Book",
  components: {
    Menu,
  },
  data() {
    return {
      addbookmodalstate: false,
      books: [],
      book: {},
    };
  },
  created() {
    this.getBooks();
  },
  methods: {
    deleteBook(bid){
      console.log('删除',bid)
      axios.delete(`http://localhost:3000/books/${bid}`)
      .then(data=>{
        this.getBooks();
      })
    },
    getBooks() {
      axios.get("http://localhost:3000/books").then((data) => {
        console.log(data);
        this.books = data.data;
      });
    },
    addbook() {
      console.log(this.book);
      axios.post("http://localhost:3000/books/", this.book).then((data) => {
        console.log(data);
        this.addbookmodalstate = false;
        this.book = {};
        this.books.push(data.data);
        // this.getBooks();  // 要耗费事件的
      });
    },
    showAddbook() {
      this.addbookmodalstate = true;
    },
    goDetail(bid) {
      console.log(bid);
      this.$router.push({
        name: "BookDetail",
        params: {
          bid,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
h2 {
  color: red;
}
.addbookmodal {
  width: 250px;
  border: 1px solid #aaa;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  input {
    width: 100%;
    height: 35px;
  }
  button {
    width: 100%;
    height: 35px;
  }
}
</style>